package com.witdata.common.service.community.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.mysql.base.service.CommunityTagBaseService;
import com.witdata.common.domain.dto.TagDto;
import com.witdata.mysql.domain.entity.TCommunityTag;
import com.witdata.common.service.community.CommunityTagService;
import com.witdata.common.service.system.TagService;
import com.witdata.common.util.IdUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CommunityTagServiceImpl implements CommunityTagService {
    private final TagService tagService;
    private final CommunityTagBaseService communityTagBaseService;

    @Override
    public List<TagDto> getCommunityTagList(Long communityId) {
        List<TCommunityTag> tCommunityTagList = communityTagBaseService.list(new QueryWrapper().eq("community_id", communityId));
        if (!CollectionUtils.isEmpty(tCommunityTagList)) {
            List<Long> tagIdList = tCommunityTagList.stream().map(TCommunityTag::getTagId).toList();
            return tagService.getTagListByIdList(tagIdList);
        }
        return null;
    }

    @Override
    public void addDefaultTag(Long communityId) {
        List<TagDto> tagDtoList = tagService.getTagListByType("base-community");
        if (!CollectionUtils.isEmpty(tagDtoList)) {
            tagDtoList.forEach(tagDto -> {
                TCommunityTag tCommunityTag = TCommunityTag.builder()
                        .id(IdUtils.createId())
                        .tagId(tagDto.getId())
                        .communityId(communityId)
                        .created(LocalDateTime.now())
                        .updated(LocalDateTime.now())
                        .build();
                communityTagBaseService.save(tCommunityTag);
            });
        }
    }
}
